package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 酒店搜索和分页
     * @param params
     * @return
     */
    @Override
    public PageResult search(RequestParams params) throws IOException {
        // 获取分页信息
        // 当前页
        Integer page = params.getPage();
        // 每页显示条数
        Integer size = params.getSize();
        // 查询ES
        //1.创建请求语义对象
        SearchRequest request = new SearchRequest("hotel");
        //描述请求类型-bool查询
        buildBasicQuery(params,request);
        // 分页
        request.source().from((page-1)*size);
        request.source().size(size);
        // 获取当前所在的位置坐标
        String location = params.getLocation();
        if(location!=null && location.length()>0){
            // 排序,根据距离排序
            request.source().sort(SortBuilders
                    .geoDistanceSort("location",new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }
        //2.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //3.解析响应结果
        PageResult pageResult = handleResponse(response);
        return pageResult;
    }

    /**
     * 描述请求类型
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.城市条件
        if (params.getCity() != null && !params.getCity().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 4.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 5.星级条件
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        // 2.算分函数查询: 构建算分函数查询对象
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10000)
                                )
                        });
        // 7.放入source
        request.source().query(functionScoreQuery);
        //request.source().query(boolQuery);
    }

    /**
     * 处理响应结果
     * @param response
     */
    public PageResult handleResponse(SearchResponse response){
        // 获取命中的所有数据(总条数和文档数据)
        SearchHits hits = response.getHits();
        // 获取总条数信息
        Long total = hits.getTotalHits().value;
        System.out.println("命名的总条数为: "+total);
        // 获取命中的文档数据
        SearchHit[] docHits = hits.getHits();
        // 创建list集合,用于收集解析到的文档数
        List<HotelDoc> list = new ArrayList<>();
        // 遍历数据
        for (SearchHit docHit : docHits) {
            // 解析文档数据
            String docJson = docHit.getSourceAsString();
            //System.out.println(docJson);
            // 将文档数据转成java对象
            HotelDoc hotelDoc = JSON.parseObject(docJson, HotelDoc.class);
            //---------------------高亮结果解析
            // 解析高亮结果数据
            Map<String, HighlightField> highlightFields = docHit.getHighlightFields();
            // 获取指定字段对应的高亮结果
            HighlightField highlightField = highlightFields.get("name");
            if (highlightField!=null){
                String hlname = highlightField.getFragments()[0].string();
                //System.out.println(hlname);
                hotelDoc.setName(hlname);
            }
            //---------------------
            //=====================解析距离
            Object[] sortValues = docHit.getSortValues();
            if (sortValues!=null && sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //System.out.println(hotelDoc);
            list.add(hotelDoc);
        }
        return new PageResult(total,list);
    }
}
